package net.homelinux.chaoswg.io.renga.krypto.converter;

import java.math.BigInteger;

import net.homelinux.chaoswg.io.higherorderfunctions.AbstractUnaryFunction;
import net.homelinux.chaoswg.io.renga.core.converter.Converter;
import net.homelinux.chaoswg.io.renga.krypto.datatypes.numerical.UnsignedNBit;
import net.homelinux.chaoswg.io.renga.krypto.datatypes.numerical.UnsignedNBitFactory;
import net.homelinux.chaoswg.io.renga.krypto.datatypes.vectors.BitVector;

public class BVtoUNBConverter extends AbstractUnaryFunction<UnsignedNBit, BitVector> implements Converter<UnsignedNBit, BitVector> {
    public final UnsignedNBit apply (final BitVector bv) {
        final UnsignedNBitFactory unbFactory = UnsignedNBitFactory.createUnsignedNBitFactory();
        final int length = bv.getSize();
        if (unbFactory.exists(length)) {
            BigInteger  bi2tmp = new BigInteger ("0");
            for (int i=0; i < length; ++i) {
                if (bv.get(i)) {
                    bi2tmp = bi2tmp.setBit((length - 1-i));
                }
            }
            UnsignedNBit toReturn = unbFactory.get(length);
            toReturn.setValue(bi2tmp);
            return toReturn;
        }
        return null;
    }
}
